package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleFeign;
import com.heima.common.constants.message.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private IArticleFeign articleFeign;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断用户是否登录
        ApUser userForFans = ApThreadLocalUtils.getUser();

        //真正未登录的用户 或 游客都不能进行关注或取消关注
        if(userForFans==null || userForFans.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.查询作者并判断是否存在
        ApAuthor author = articleFeign.findAuthorById(dto.getAuthorId());
        if(author==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者不存在");
        }

        //4.查询作者用户是否存在
        ApUser userForAuthor = apUserMapper.selectById(author.getUserId());
        if(userForAuthor==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "作者用户不存在");
        }

        //5.判断当前登录用户是否关注自己
        if(userForFans.getId().equals(userForAuthor.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "用户不能关注或取消关注自己");
        }

        //6.根据类型判断是关注还是取消关注
        if(dto.getOperation()==0){ //关注
            ResponseResult responseResult = followRelation(userForFans, userForAuthor);
            if(responseResult!=null){
                return responseResult;
            }
        } else { //取消关注
            ResponseResult responseResult = followCancelRelation(userForFans, userForAuthor);
            if(responseResult!=null){
                return responseResult;
            }
        }

        //生产关注或取消关注数据到kafka中（哪个人？关注了谁？哪条文章？操作类型？）
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setUserId(userForFans.getId()); //登录用户ID(哪个人)
        followBehaviorDto.setFollowId(userForAuthor.getId());//作者ID（关注了谁）
        followBehaviorDto.setArticleId(dto.getArticleId()); //文章ID（哪条文章）
        followBehaviorDto.setOperation(dto.getOperation()); //操作类型（0-关注 1-取消关注）

        kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));

        //7.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private ApUserFollowMapper apUserFollowMapper;

    @Autowired
    private ApUserFanMapper apUserFanMapper;

    //关注
    private ResponseResult followRelation(ApUser userForFans, ApUser userForAuthor) {
        Integer userIdForFans = userForFans.getId(); //当前登录用户ID
        Integer userIdForAuthor = userForAuthor.getId();//作者用户ID

        //查询关注信息判断是否存在
        Integer followCount = apUserFollowMapper.selectCount(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userIdForFans)
                .eq(ApUserFollow::getFollowId, userIdForAuthor));
        if(followCount>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已关注，不要重复关注1");
        }

        //查询粉丝信息判断是否存在
        Integer fanCount = apUserFanMapper.selectCount(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, userIdForAuthor)
                .eq(ApUserFan::getFansId, userIdForFans)
        );
        if(fanCount>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已关注，不要重复关注2");
        }


        //保存关注信息
        ApUserFollow apUserFollow = new ApUserFollow();
        apUserFollow.setUserId(userIdForFans);  //登录用户ID
        apUserFollow.setFollowId(userIdForAuthor); //作者用户ID
        apUserFollow.setFollowName(userForAuthor.getName()); //作者名
        apUserFollow.setIsNotice(true); //是否动态通知
        apUserFollow.setLevel((short)0);//关注度
        apUserFollow.setCreatedTime(new Date());
        apUserFollowMapper.insert(apUserFollow);


        //保存粉丝信息
        ApUserFan apUserFan = new ApUserFan();
        apUserFan.setUserId(userIdForAuthor); //作者用户ID
        apUserFan.setFansId(userIdForFans.longValue());//登录用户ID
        String fanName = apUserMapper.selectById(userIdForFans).getName();
        apUserFan.setFansName(fanName); //登录用户名
        apUserFan.setIsDisplay(true); //是否展示
        apUserFan.setLevel((short)0); //忠诚度
        apUserFan.setIsShieldComment(false); //是否屏蔽评论
        apUserFan.setIsShieldLetter(false);//是否允许私信
        apUserFan.setCreatedTime(new Date());
        apUserFanMapper.insert(apUserFan);

        return null;
    }

    //取消关注
    private ResponseResult followCancelRelation(ApUser userForFans, ApUser userForAuthor) {
        Integer userIdForFans = userForFans.getId(); //当前登录用户ID
        Integer userIdForAuthor = userForAuthor.getId();//作者用户ID

        //查询关注信息判断是否不存在
        Integer followCount = apUserFollowMapper.selectCount(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userIdForFans)
                .eq(ApUserFollow::getFollowId, userIdForAuthor));
        if(followCount==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "关注信息不存在，不能取消关注");
        }

        //查询粉丝信息判断是否不存在
        Integer fanCount = apUserFanMapper.selectCount(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, userIdForAuthor)
                .eq(ApUserFan::getFansId, userIdForFans)
        );
        if(fanCount==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "粉丝信息不存在，不要取消关注");
        }

        //删除关注记录
        apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getUserId, userIdForFans)
                .eq(ApUserFollow::getFollowId, userIdForAuthor));


        //删除粉丝记录
        apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                .eq(ApUserFan::getUserId, userIdForAuthor)
                .eq(ApUserFan::getFansId, userIdForFans));


        return null;
    }


}
